<?php

namespace youmbe\phpword\base;

use Yii;
use PhpOffice\PhpWord\Exception\Exception;

/**
 * PHPWord main class
 *
 */
class PhpWord extends \PhpOffice\PhpWord\PhpWord {

    /**
     * Collection of sections
     *
     * @var \PhpOffice\PhpWord\Element\Section[]
     */
    private static $extensions = [
        'ODText' => 'odt',
        'RTF' => 'rtf',
        'Word2007' => 'docx',
        'HTML' => 'html',
        'PDF' => 'pdf'
    ];

    public function getFileInfo($name = null, $format = 'Word2007') {
        if (!$name) {
            $name = self::DEFAULT_EXPORT_FILE_NAME;
        }
        $pathinfo = pathinfo($name);
        $extension = isset($pathinfo['extension']) ? $pathinfo['extension'] : '';
        if (!$extension) {
            if (!in_array($format, array_keys(self::$extensions), true)) {
                throw new Exception("\"{$format}\" is not a valid writer.");
            }
            $extension = self::$extensions[$format];
        }
        if (!in_array($extension, self::$extensions, true)) {
            throw new Exception("\"{$extension}\" is not a valid format.");
        }
        return [
            'path' => isset($pathinfo['dirname']) ? str_replace('.', '', $pathinfo['dirname']) : '',
            'filename' => $pathinfo['filename'] . '.' . $extension,
        ];
    }

    const DEFAULT_EXPORT_FILE_NAME = 'export';

    /**
     * Save to file or download
     * All exceptions should already been handled by the writers
     *
     * @param string $name
     * @param string $format
     * @param bool $download
     * @return bool
     */
    public function render($name = null, $format = 'Word2007', $download = false) {
        return $this->save($name, $format, $download);
    }

    /**
     * Save to file or download
     *
     * All exceptions should already been handled by the writers
     *
     * @param string $filename
     * @param string $format
     * @param bool $download
     * @return bool
     */
    public function save($filename, $format = 'Word2007', $download = false) {
        if ($download === true) {
            header('Access-Control-Allow-Origin: *');
        }
        return parent::save($filename, $format, $download);
    }

}
